package com.bci.pwtz.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bci.pwtz.common.PwtzConstants;
import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.common.util.PwtzUtils;
import com.bci.pwtz.exception.CanNotDeleteException;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.exception.PwtzException;
import com.bci.pwtz.mysql.model.CompanyUser;
import com.bci.pwtz.mysql.model.Zydlfzx;
import com.bci.pwtz.mysql.model.Zygt;
import com.bci.pwtz.mysql.model.Zyhwg;
import com.bci.pwtz.mysql.model.Zykgz;
import com.bci.pwtz.mysql.model.Zypds;
import com.bci.pwtz.mysql.model.Zyxl;
import com.bci.pwtz.mysql.model.Zyxsbdz;
import com.bci.pwtz.service.BusinessCommonService;
import com.bci.pwtz.service.CompanyService;
import com.bci.pwtz.service.ZydlfzxService;
import com.bci.pwtz.service.ZygtService;
import com.bci.pwtz.service.ZyhwgService;
import com.bci.pwtz.service.ZykgzService;
import com.bci.pwtz.service.ZypdsService;
import com.bci.pwtz.service.ZyxlService;
import com.bci.pwtz.service.ZyxsbdzService;

@Controller
@RequestMapping("/user/zygt")
public class ZygtController extends AbstractController
{
@Autowired
ZygtService service;
@Autowired
ZykgzService zykgzService;
@Autowired
ZypdsService zypdsService;
@Autowired
ZyhwgService zyhwgService;
@Autowired
ZyxsbdzService zyxsbdzService;
@Autowired
ZydlfzxService zydlfzxService;
@Autowired
ZyxlService lineService;
@Autowired
private CompanyService  companyService;
@Autowired
private BusinessCommonService businessCommonService;

@RequestMapping(value="/list",method=RequestMethod.POST)
@ResponseBody
public PaginationList<Zygt> getDygtList(String deviceName,String startsubstationcode,int pageNo,int pageSize){
    PaginationList<Zygt> list=null;
    Long companyId = getLastCompanyId();
    int predevicetype=0;
    String predevicename="";
    String linename="";
    String physictowername="";
    try{
        Zyxl line=lineService.load(startsubstationcode);
        if(line!=null){
            linename=line.getDevicename();
        }
        list = service.list(deviceName,companyId,0,null,startsubstationcode,null,null,pageSize,pageNo,null);
        if(list!=null&&list.getRecords()!=null&&list.getRecords().size()>0){
            for(Zygt device : list.getRecords()){
                predevicetype=device.getPredevicetype();
                if(predevicetype==124){
                    Zykgz obj=zykgzService.load(device.getPredevicecode());
                    if(obj!=null){
                        device.setPredevicecode(obj.getDevicename());
                    }else{
                        device.setPredevicecode(predevicename);
                    }
                }else if(predevicetype==125){
                    Zypds obj=zypdsService.load(device.getPredevicecode());
                    if(obj!=null){
                        device.setPredevicecode(obj.getDevicename());
                    }else{
                        device.setPredevicecode(predevicename);
                    }
                }else if(predevicetype==126){
                    Zyhwg obj=zyhwgService.load(device.getPredevicecode());
                    if(obj!=null){
                        device.setPredevicecode(obj.getDevicename());
                    }else{
                        device.setPredevicecode(predevicename);
                    }
                }else if(predevicetype==127){
                    Zyxsbdz obj=zyxsbdzService.load(device.getPredevicecode());
                    if(obj!=null){
                        device.setPredevicecode(obj.getDevicename());
                    }else{
                        device.setPredevicecode(predevicename);
                    }
                }else if(predevicetype==128){
                    Zydlfzx obj=zydlfzxService.load(device.getPredevicecode());
                    if(obj!=null){
                        device.setPredevicecode(obj.getDevicename());
                    }else{
                        device.setPredevicecode(predevicename);
                    }
                }else if(predevicetype==102){
                    Zygt obj=service.load(device.getPredevicecode());
                    if(obj!=null){
                        device.setPredevicecode(obj.getDevicename());
                    }else{
                        device.setPredevicecode(predevicename);
                    }
                }else{
                    device.setPredevicecode(predevicename);
                }
                Zygt physictower=service.load(device.getPhysicaltowercode());
                if(physictower!=null){
                    device.setPhysicaltowercode(physictower.getNote());
                }else{
                    device.setPhysicaltowercode(physictowername);
                }
                device.setLinecode(linename);
            }
        }
    }catch(Exception e){
        e.printStackTrace();
    }
    return list;
}

@RequestMapping(value = "/edite", method = RequestMethod.POST)
@ResponseBody
public Map<String, String> edite(String data)
{
    Map<String, String> map = new HashMap<String, String>();
    try
    {
        //data=java.net.URLDecoder.decode(data,"UTF-8");
        String [] list=decodeURL(data.split("&"));
        for(int i=0;i<list.length;i++){
            String[] array=list[i].split("=");
            if(array.length==1){
                map.put(array[0], "");
            }else{
                map.put(array[0], array[1]);
            }
        }
        int retCount = businessCommonService.getCountByDeviceName(getLastCompanyId(),(long)AbstractController.中压杆塔, map.get("devicename"),map.get("deviceid"));
        if(retCount>0){
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "名称已存在！");
            return map;
        }
        CompanyUser user=(CompanyUser) session.getAttribute("user");
        Zygt device=new Zygt();
        device.setDeviceid(map.get("deviceid"));
        device.setDevicename(map.get("devicename"));
        device.setAltitude(map.get("altitude"));
        device.setAssetnumber(map.get("assetnumber"));
        device.setAssetsnature(map.get("assetsnature"));
        device.setAssetunit(map.get("assetunit"));
        device.setCompanyid(user.getLastCompanyId());
        device.setCreateid(user.getCompanyUserId());
        device.setDevicenumber(map.get("devicenumber"));
        device.setEquipmentstate(map.get("equipmentstate"));
        device.setGroundingresistance(PwtzUtils.passDouble(map.get("groundingresistance")));
        device.setIsgenerationdimension(map.get("isgenerationdimension"));
        device.setIsruralpowernetwork(map.get("isruralpowernetwork"));
        device.setLastoperatorid(user.getCompanyUserId());
        device.setLatitude(map.get("latitude"));
        device.setLinecode(map.get("linecode"));
        device.setLocalcity(map.get("localcity"));
        device.setLongitude(map.get("longitude"));
        device.setMainlinecode(map.get("mainlinecode"));
        device.setMaintenanceteam(map.get("maintenanceteam"));
        device.setModel(map.get("model"));
        device.setNote(map.get("note"));
        device.setOperationstate(map.get("operationstate"));
        device.setOperationunit(map.get("operationunit"));
        device.setProductionfactory(map.get("productionfactory"));
        device.setSerialnumber(map.get("serialnumber"));
        device.setSyncstatus(0);
        device.setVoltagelevel(map.get("voltagelevel"));
        device.setBasicform(map.get("basicform"));
        device.setCommissioningdate(PwtzUtils.parseDate(map.get("commissioningdate"),"yyyy-MM-dd"));
        device.setConstructionunit(map.get("constructionunit"));
        device.setCrossarmcount(PwtzUtils.passLong(map.get("crossarmcount")));
        device.setCrossarmmaterial(map.get("crossarmmaterial"));
        device.setGroundingresistance(PwtzUtils.passDouble(map.get("groundingresistance")));
        device.setIndexnumber(PwtzUtils.passLong(map.get("indexnumber")));
        device.setIssametower(map.get("issametower"));
        device.setIsterminal(map.get("isterminal"));
        String physicaltowercode=(String)map.get("physicaltowercode");
        if("-99".equals(physicaltowercode)){
            physicaltowercode=map.get("deviceid");
            device.setNote(map.get("devicename"));
        }
        device.setPhysicaltowercode(physicaltowercode);
        device.setPredevicecode(map.get("predevicecode"));
        device.setPredevicetype(PwtzUtils.passInt(map.get("predevicetype")));
        device.setRegionalcharacteristics(map.get("regionalcharacteristics"));
        device.setRotationdegree(map.get("rotationdegree"));
        device.setRotationdirection(map.get("rotationdirection"));
        device.setSpan(PwtzUtils.passDouble(map.get("span")));
        device.setTowerheight(PwtzUtils.passDouble(map.get("towerheight")));
        device.setTowermaterial(map.get("towermaterial"));  
        device.setTowernature(map.get("towernature"));
        device.setFactorydate(PwtzUtils.parseDate(map.get("factorydate"),"yyyy-MM-dd"));
        int ret = service.update(device);
        if (ret > 0)
        {
            setLog(device.getDeviceid(), device.getCompanyid(), AbstractController.中压杆塔, AbstractController.update, "修改中压杆塔["+device.getDevicename()+"]成功", getUserId());
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "编辑中压杆塔成功");
            map.put("deviceid", device.getDeviceid());
        }
        else
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "编辑中压杆塔失败");
        }
    }
    catch (PwtzDatabaseException e)
    {
        map = packageException(e);
    }
    catch (UnsupportedEncodingException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return map;
}
@RequestMapping(value = "/load", method = RequestMethod.POST)
@ResponseBody
public Zygt load(String deviceId) throws PwtzException
{
    Zygt zsbyq = null;
    try
    {
        if (null != deviceId)
        {
            zsbyq = service.load(deviceId);
        }
    }
    catch (PwtzDatabaseException e)
    {
        e.printStackTrace();
    }
    return zsbyq;
}

@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public Map<String, String> add(String data) throws PwtzDatabaseException
{
    Map<String, String> map = new HashMap<String, String>();
    boolean isVip =  companyService.isVip(getLastCompanyId());
    if(!isVip){
        int companyTowers = service.getCompanyTowerCount(getLastCompanyId());
        if(companyTowers>=PwtzConstants.THE_TRIAL_TOWERS_COUNT){
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,null, "单位中压杆塔数超过限制");
            return map;
        }
    }
    try
    {
        //data=java.net.URLDecoder.decode(data,"UTF-8");
        String [] list=decodeURL(data.split("&"));
        for(int i=0;i<list.length;i++){
            String[] array=list[i].split("=");
            if(array.length==1){
                map.put(array[0], "");
            }else{
                map.put(array[0], array[1]);
            }
        }
        int retCount = businessCommonService.getCountByDeviceName(getLastCompanyId(),(long)AbstractController.中压杆塔, map.get("devicename"));
        if(retCount>0){
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "名称已存在！");
            return map;
        }
        CompanyUser user=(CompanyUser) session.getAttribute("user");
        Zygt device=new Zygt();
        UUID uuid=UUID.randomUUID();
        device.setDeviceid(uuid.toString());
        device.setDevicename(map.get("devicename"));
        device.setAltitude(map.get("altitude"));
        device.setAssetnumber(map.get("assetnumber"));
        device.setAssetsnature(map.get("assetsnature"));
        device.setAssetunit(map.get("assetunit"));
        device.setCompanyid(user.getLastCompanyId());
        device.setCreateid(user.getCompanyUserId());
        device.setDevicenumber(map.get("devicenumber"));
        device.setEquipmentstate(map.get("equipmentstate"));
        device.setGroundingresistance(PwtzUtils.passDouble(map.get("groundingresistance")));
        device.setIsgenerationdimension(map.get("isgenerationdimension"));
        device.setIsruralpowernetwork(map.get("isruralpowernetwork"));
        device.setLastoperatorid(user.getCompanyUserId());
        device.setLatitude(map.get("latitude"));
        device.setLinecode(map.get("linecode"));
        device.setLocalcity(map.get("localcity"));
        device.setLongitude(map.get("longitude"));
        device.setMainlinecode(map.get("mainlinecode"));
        device.setMaintenanceteam(map.get("maintenanceteam"));
        device.setModel(map.get("model"));
        device.setNote(map.get("note"));
        device.setOperationstate(map.get("operationstate"));
        device.setOperationunit(map.get("operationunit"));
        device.setProductionfactory(map.get("productionfactory"));
        device.setSerialnumber(map.get("serialnumber"));
        device.setSyncstatus(0);
        device.setVoltagelevel(map.get("voltagelevel"));
        device.setBasicform(map.get("basicform"));
        device.setCommissioningdate(PwtzUtils.parseDate(map.get("commissioningdate")));
        device.setConstructionunit(map.get("constructionunit"));
        device.setCrossarmcount(PwtzUtils.passLong(map.get("crossarmcount")));
        device.setCrossarmmaterial(map.get("crossarmmaterial"));
        device.setGroundingresistance(PwtzUtils.passDouble(map.get("groundingresistance")));
        device.setIndexnumber(PwtzUtils.passLong(map.get("indexnumber")));
        device.setIssametower(map.get("issametower"));
        device.setIsterminal(map.get("isterminal"));
        String physicaltowercode=(String)map.get("physicaltowercode");
        if("0".equals(physicaltowercode)){
            physicaltowercode=uuid.toString();
//            device.setNote(map.get("devicename"));
        }
        device.setPhysicaltowercode(physicaltowercode);
        device.setPredevicecode(map.get("predevicecode"));
        device.setPredevicetype(PwtzUtils.passInt(map.get("predevicetype")));
        device.setRegionalcharacteristics(map.get("regionalcharacteristics"));
        device.setRotationdegree(map.get("rotationdegree"));
        device.setRotationdirection(map.get("rotationdirection"));
        device.setSpan(PwtzUtils.passDouble(map.get("span")));
        device.setTowerheight(PwtzUtils.passDouble(map.get("towerheight")));
        device.setTowermaterial(map.get("towermaterial"));
        device.setTowernature(map.get("towernature"));
        device.setFactorydate(PwtzUtils.parseDate(map.get("factorydate")));
        device = service.add(device);
        if (device !=null)
        {
            setLog(device.getDeviceid(), device.getCompanyid(), AbstractController.中压杆塔, AbstractController.add, "添加中压杆塔["+device.getDevicename()+"]成功", getUserId());
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "添加中压杆塔成功");
            map.put("deviceid", uuid.toString());
            session.removeAttribute(device.getLinecode());
            session.setAttribute(device.getLinecode(), device);
        }
        else
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "添加中压杆塔失败");
        }
    }
    catch (PwtzDatabaseException e)
    {
        map = packageException(e);
    }
    catch (UnsupportedEncodingException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return map;
}

@RequestMapping(value="dlist",method=RequestMethod.POST)
@ResponseBody
public List<Zygt> getList(Long companyId,String deviceid,String currentDeviceId){
    List<Zygt> list=new ArrayList<Zygt>();
    try{
        PaginationList<Zygt> plist=service.list(null, companyId, 1, null,deviceid, null, null, 0, 0,currentDeviceId);
        if(plist!=null&&plist.getTotalRecord()>0){
            list=plist.getRecords();
        }
    }catch(Exception e){
        e.printStackTrace();
    }
    return list;
}

@RequestMapping(value="/delete",method=RequestMethod.POST)
@ResponseBody
public Map<String,String> delete(String deviceid){
    Map<String,String> map=new HashMap<String, String>();
    int result=0;
    try
    {
        Zygt device=service.load(deviceid);
        if(device!=null)
        result=service.delete(deviceid);
        if (result>0)
        {
            setLog(device.getDeviceid(), device.getCompanyid(), AbstractController.中压杆塔, AbstractController.delete, "删除中压杆塔["+device.getDevicename()+"]成功", getUserId());
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "删除中压杆塔成功");
        }
        else
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "删除中压杆塔失败");
        }
    }
    catch (PwtzDatabaseException e)
    {
        map = packageException(e);
    }
    catch (CanNotDeleteException e)
    {
        map = packageException(e);
    }
    return map;
}

@RequestMapping(value = "/getsametowernumber", method = RequestMethod.POST)
@ResponseBody
public int getSameTowerNumber(String deviceid) throws PwtzException
{
    int result=0;
    try
    {
        if (null != deviceid)
        {
            result = service.getSameTowerList(deviceid).size();
        }
    }
    catch (PwtzDatabaseException e)
    {
        e.printStackTrace();
    }
    return result;
}
@RequestMapping(value = "/getphysicaltowerlist", method = RequestMethod.POST)
@ResponseBody
public List<Zygt> getPhysicalTowerList(String deviceid) throws PwtzException
{
    List<Zygt> list=null; 
    try
    {
       Long companyid=getLastCompanyId();
       list=service.getPhysicalTowerList(deviceid,companyid);
    }
    catch (PwtzDatabaseException e)
    {
        e.printStackTrace();
    }
    return list;
}
}
